package ajaxjs.lang;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;

import javax.servlet.http.HttpServletRequest;

/**
 * 		
 * var obj = com.ajaxjs.Bridge.newInstanceByClassName("ajaxjs.data.entry.News");
println(obj);
 * @author sp42
 */
public class Bridge {
	
	/**
	 * 无构造参数的
	 * @param className
	 * @return
	 */
	public static Object newInstanceByClassName(String className){
		Class<?> clazz = null;
		
		try {
			clazz = Class.forName(className);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}

	    // 2. 获取指定参数类型的构造函数，这里传入我们想调用的构造函数所需的参数类型
		Constructor<?> constructor = null;
		try {
			constructor = clazz.getConstructor();
		} catch (NoSuchMethodException e1) {
			e1.printStackTrace();
		} catch (SecurityException e1) {
			e1.printStackTrace();
		}
		
		// 3. 根据构造函数，创建指定类型的对象,传入的参数个数需要与上面传入的参数类型个数一致
		Object obj = null;
		try {
			obj = constructor.newInstance();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		
		if(obj == null)System.out.println("实例化对象失败：" + className);
		
		return obj;
	}
	
	public static Object newInstanceByClassName(String className, HttpServletRequest request, Connection jdbcConn){
		Class<?> clazz = null;
		
		try {
			clazz = Class.forName(className);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		
		// 2. 获取指定参数类型的构造函数，这里传入我们想调用的构造函数所需的参数类型
		Constructor<?> constructor = null;
		
		try {
			constructor = clazz.getConstructor(HttpServletRequest.class, Connection.class);
		} catch (NoSuchMethodException e1) {
			System.out.println("没有这个构造器：" + className + request + jdbcConn);
			e1.printStackTrace();
		} catch (SecurityException e1) {
			e1.printStackTrace();
		}
		
		// 3. 根据构造函数，创建指定类型的对象,传入的参数个数需要与上面传入的参数类型个数一致
		if(constructor != null){
			Object obj = null;
			try {
				obj = constructor.newInstance(request, jdbcConn);
			} catch (InstantiationException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			}
			
			if(obj == null)System.out.println("实例化对象失败：" + className);
			
			return obj;
		}else return null;
	}
}
